<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<p>策略模式：封装一系列的算法，他们之间可以相互替换</p>
	<form id="myFForm">
		<input type="text" name="name"><br>
		<input type="text" name="password"><br>
		<input type="text" name="mobile"><br>
		<input type="button" id="submit" value="提交">
	</form>
	<script type="text/javascript">
		// 表单验证
		const stratageForm = {
			isEmpty: function (value, msg) {
				if (!value) {
					return msg;
				}
			},
			minLength: function (value, minLength, msg) {
				if (value.length < minLength) {
					return msg;
				}
			},
			isMobile: function (value, msg) {
				if (!/(^1[3|5|8][0-9]{9}$)/.test(value)) {
					return msg;
				}

			},
			maxLength: function (value, length, msg) {
				if (value.length > length) {
					return msg;
				}
			}
		}
		//添加验证规则
		class validator {
			constructor (stratageForm) {
				this.cache = [];
				this.stratageForm = stratageForm;
			}
			add (dom, rule, msg) {
				let _self = this;
				if (Object.prototype.toString.call(rule) === '[object Array]') {
					((rule) => {
						for (let i = 0; i < rule.length; i++) {
							let ary = rule[i].strategy.split(':'),
								validatorName = ary.shift(),
								errormsg = rule[i].errormsg;
								ary.unshift(dom.value);
								if (!errormsg) {
									console.error('请填写错误信息反馈！');
									return;
								} else {
									ary.push(errormsg);
									_self.cache.push(() => {
										return _self.stratageForm[validatorName].apply(dom, ary)
									})
								}
								
						}
					})(rule)
				} else {
					console.error("请输入正确的验证规则[{rule:xxx,msg:'xxxxx'}]")
				}
			}
			start () {
				for (let i = 0 ,validatorFucn; i < this.cache.length; i++) {
					validatorFucn = this.cache[i];
					let msg = validatorFucn();
					if (msg) {
						return msg;
					}
				}
			}
		}
		//验证表单
		let formValidator = (formId) => {
			let valid = new validator(stratageForm),
				dom = document.querySelector('#' + formId);
				valid.add(dom.name, [{
					strategy : 'isEmpty',
					errormsg : '用户名不能为空！'
				}]);
				valid.add(dom.password, [{
					strategy : 'isEmpty',
					errormsg : '密码不能为空！'
				},{
					strategy : 'minLength:6',
					errormsg : '密码长度不能小于6个字符！'
				},{
					strategy : 'maxLength:12',
					errormsg : '密码长度不能大于12个字符！'
				}]);
				valid.add(dom.mobile, [{
					strategy : 'isEmpty',
					errormsg : '用户名不能为空'
				},{
					strategy : 'isMobile',
					errormsg : '手机格式不对！'
				}]);
				let msg = valid.start();
				if (msg) {
					alert(msg)
					return false;
				} else {
					console.log('校验成功');
				}
				

		}
		document.querySelector('#submit').onclick = () => {
			formValidator('myFForm');
		}

	</script>
</body>
</html>